#!/bin/bash

# 如果调用命令时传递的参数的个数 小于4个，则报错
if [ $# -lt 4 ] ;then
  echo "call command error."
  echo "USAGE: $0 docker_image_prefix docker_image_rep docker_image_tag -r -b"
  exit
fi

docker_image_prefix=$1
docker_image_repo=$2
docker_image_tag=$3
docker_image_name=$docker_image_prefix/$docker_image_repo:$docker_image_tag

echo "docker_image_name=$docker_image_name"

params="$*"
echo "params=$params"

query_ps()
{
  image_repo=$1
  image_tag=$2

  echo "docker images|grep $image_repo|grep $image_tag"
  docker images|grep $image_repo|grep $image_tag
}

delete_container()
{
  echo "delete running container by $docker_image_name"
  ids=$(docker ps -a|grep "$docker_image_name"|awk '{print $1}')
  echo "ids:$ids"
  if [ -n "$ids" ]; then
    docker rm -f $ids
  fi
}

build_image()
{
image_repo=$1
image_tag=$2
image_name=$3

delete_container

query_ps $image_repo $image_tag

echo "remove image $image_name"
docker rmi $image_name -f

echo "build image $image_name"
docker build -t $image_name .

query_ps $image_repo $image_tag
}

run_container()
{
container_name=$1
image_name=$2

echo "docker ps|grep $container_name"
docker ps -a|grep $container_name

echo "delete container "
docker rm -f $container_name

echo "docker ps|grep $container_name"
docker ps -a|grep $container_name

echo "start container $container_name by $image_name"

docker run --name $container_name \
-d $image_name \
 tail -f /dev/null
# sh -c "tail -f /dev/null"
}

if [[ $(echo $params | grep -E "\-?b") != "" ]]; then
 build_image "$docker_image_repo" "$docker_image_tag" "$docker_image_name"
fi


if [[ $(echo $params | grep -E "\-?r") != "" ]]; then
 run_container "$docker_image_repo" "$docker_image_name"
fi

